/**
 *
 */
package jp.seraph.same.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 */
public abstract class AbstractMapHierarchicalViewModel<ChildType extends ViewModel> extends AbstractHierarchicalViewModel<ChildType> implements HierarchicalViewModel<ChildType> {
    public AbstractMapHierarchicalViewModel(String aName) {
        super(aName);
        mChildMap = new HashMap<String, ChildType>();
        mAddedListeners = new ArrayList<ChildAddedListener<ChildType>>();
        mRemovedListeners = new ArrayList<ChildRemovedListener<ChildType>>();
    }

    private Map<String, ChildType> mChildMap;
    protected Map<String, ChildType> getChildMap(){
        return mChildMap;
    }

    /**
     * @see jp.seraph.same.model.HierarchicalViewModel#add(jp.seraph.same.model.ViewModel)
     */
    public void add(ChildType aChild) {
        mChildMap.put(aChild.getName(), aChild);
        fireChangedEvent();
        fireAddedEvent(aChild);
    }

    /**
     * @see jp.seraph.same.model.HierarchicalViewModel#contains(jp.seraph.same.model.ViewModel)
     */
    public boolean contains(ChildType aChild) {
        return this.contains(aChild.getName());
    }

    /**
     * @see jp.seraph.same.model.HierarchicalViewModel#contains(java.lang.String)
     */
    public boolean contains(String aChildName) {
        return mChildMap.containsKey(aChildName);
    }

    /**
     * @see jp.seraph.same.model.HierarchicalViewModel#get(java.lang.String)
     */
    public ChildType get(String aChildName) {
        return mChildMap.get(aChildName);
    }

    /**
     * @see jp.seraph.same.model.HierarchicalViewModel#remove(jp.seraph.same.model.ViewModel)
     */
    public ChildType remove(ChildType aChild) {
        return this.remove(aChild.getName());
    }

    /**
     * @see jp.seraph.same.model.HierarchicalViewModel#remove(java.lang.String)
     */
    public ChildType remove(String aChildName) {
        ChildType tRemoved = mChildMap.remove(aChildName);
        if(tRemoved != null){
            fireRemovedEvent(tRemoved);
        }

        return tRemoved;
    }

    /**
     * @see jp.seraph.same.model.HierarchicalViewModel#getChildCount()
     */
    public int getChildCount() {
        return mChildMap.size();
    }

    /**
     * @see java.lang.Iterable#iterator()
     */
    public Iterator<ChildType> iterator() {
        return mChildMap.values().iterator();
    }
}
